package com.example.springboot1.api;

import com.example.springboot1.entity.ByteArrayMultipartFile;
import com.example.springboot1.utils.BussinessException;
import com.example.springboot1.utils.HttpKit;
import com.example.springboot1.utils.ZipUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipOutputStream;

/**
 * @author ckj
 * @description TODO
 * @date 2024-02-02 16:17
 */

@RestController
public class DownZipApi {

    @RequestMapping("/downZip")
    public ResponseEntity<byte[]> downZip() {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);
        String zipFileName = "测试";
        List<String> ids = new ArrayList<>();
        for (String id : ids) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ZipUtils.doZip(baos.toByteArray(), zipOutputStream, id + ".xls");
        }
        ZipUtils.close(zipOutputStream);
        // 返回文件压缩包
        try {
            byte[] fileBytes = byteArrayOutputStream.toByteArray();
            HttpHeaders headers = new HttpHeaders();
            String userAgent = HttpKit.getRequest().getHeader("User-Agent");
            if (userAgent.toLowerCase().contains("trident") || userAgent.toLowerCase().contains("edge")) {
                // IE，Edge浏览器
                zipFileName = URLEncoder.encode(zipFileName, "UTF-8");
            } else {
                zipFileName = new String(zipFileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            }
            headers.add("Content-Disposition", "attachment; filename=\"" + zipFileName + ".zip" + "\"");
            HttpStatus httpStatus = HttpStatus.OK;
            return new ResponseEntity(fileBytes, headers, httpStatus);
        } catch (UnsupportedEncodingException e) {
            throw new BussinessException("压缩文件名转码失败");
        }
    }

    public void upload(){
        byte[] bytes=new byte[1024];
        MultipartFile file = new ByteArrayMultipartFile("file", "测试", MediaType.MULTIPART_FORM_DATA_VALUE, bytes);

    }
}
